<!-- 商品参数设置 -->
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体内容 -->
    <el-card>
      <el-alert title="注意：只能为第三级分类设置参数" type="warning" :closable="false" show-icon></el-alert>
      <el-row>
        <el-col :span="3">选择商品分类：</el-col>
        <el-col :span="10">
          <el-cascader
            v-model="cascaderValue"
            :options="parentCateData"
            :props="cateProps"
            @change="cascaderChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isDisabled" @click="addParams">添加参数</el-button>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isDisabled" @click="addParams">添加属性</el-button>
        </el-tab-pane>
      </el-tabs>
      <!-- 动态参数或静态属性数据列表 -->
      <el-table :data="tableData" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-tag
              type
              v-for="(item, i) in scope.row.attr_vals"
              :key="i"
              closable
              @close="tagClose(scope.row, i)"
            >{{item.attr_val}}</el-tag>
            <el-input
              class="input-new-tag"
              v-if="scope.row.tagTnputVisible"
              v-model="scope.row.tagInputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm(scope.row)"
              @blur="handleInputConfirm(scope.row)"
            ></el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showTagInput(scope.row)"
            >+ New Tag</el-button>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="attr_name" :label="tableTitle"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="editParams(scope.row)">修改</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteParams(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加属性对话框 -->
    <el-dialog
      :title="paramsTitle"
      :visible.sync="paramsDialogVisible"
      @close="closeParamsDialog"
      width="50%"
    >
      <el-form :model="paramsForm" :rules="paramsRules" ref="paramsRef" label-width="100px">
        <el-form-item :label="tableTitle" prop="attr_name">
          <el-input v-model="paramsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="paramsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 引入axios接口
import {
  reqParentCateList,
  reqCateParams,
  reqUpdateParams,
  reqAddParams,
  reqDeleteParams,
  reqAddTag,
  reqDeleteTag
} from '@/api'

export default {
  data() {
    return {
      parentCateData: [], // 级联选择数据源
      cascaderValue: [], // 级联选择的值
      cateProps: {
        // 设置分类表格展示属性
        expandTrigger: 'hover',
        label: 'name',
        value: 'id'
      },
      activeName: 'many', // 当前选择动态参数还是动态属性
      tableData: [], // 动态参数或静态属性数据源
      paramsDialogVisible: false, // 动态参数和静态属性模态框显示与隐藏
      paramsForm: {
        // 动态和静态添加属性对话框的值
        cat_id: '', // 产品id
        attr_id: '', // 属性id
        attr_name: '', // 属性名
        attr_write: 'manual', // manual:手工录入 list:从列表选择
        attr_sel: '' // 判断动态参数和静态属性
      },
      paramsRules: {
        // 动态和静态添加属性对话框的校验规则
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      isAddDialog: true // 添加或修改对话框判断值,true是增加，false是编辑
    }
  },

  computed: {
    // 控制添加属性按钮的是否禁用状态
    isDisabled() {
      if (this.cascaderValue.length !== 3) {
        return true
      }
      return false
    },
    // 级联选择的分类ID
    cateId() {
      if (this.cascaderValue.length === 3) {
        return this.cascaderValue[2]
      }
      return null
    },
    // 控制对话框中标题显示
    paramsTitle() {
      if (this.activeName === 'many') {
        if (this.isAddDialog) {
          return '添加动态参数'
        } else {
          return '修改参数名称'
        }
      } else {
        if (this.isAddDialog) {
          return '添加静态属性'
        } else {
          return '修改属性名称'
        }
      }
    },
    // 控制数据列表中标题显示
    tableTitle() {
      if (this.activeName === 'many') {
        return '参数名称'
      } else {
        return '属性名称'
      }
    }
  },

  created() {
    // 初始化级联分类
    this.getCateList()
  },

  methods: {
    // 获取级联分类列表
    async getCateList() {
      const result = await reqParentCateList(3)
      this.parentCateData = result.data
    },

    // 获取参数列表公共函数
    async getCateParams() {
      const result = await reqCateParams(this.cateId, this.activeName)
      // 给每行的input设置单独的值，修复多个input共用一个v-model的值的问题
      result.data.forEach(item => {
        item.tagTnputVisible = false
        item.tagInputValue = ''
      })
      if (this.activeName === 'many') {
        this.tableData = result.data
      } else {
        this.tableData = result.data
      }
    },

    // 级联选择
    cascaderChange() {
      // console.log(this.cascaderValue)
      // console.log(this.cateId)
      // 获取商品参数
      this.getCateParams()
    },

    // 主题标签切换
    handleTabClick() {
      // console.log(this.activeName)
      this.getCateParams()
    },

    // 添加属性
    addParams() {
      // 设置属性
      this.paramsForm.cat_id = this.cateId
      this.paramsForm.attr_sel = this.activeName

      this.isAddDialog = true
      this.paramsDialogVisible = true
    },

    // 修改属性
    editParams(row) {
      // 正常开发中要往后台发送数据请求，才能保证数据的及时性
      this.paramsForm.cat_id = row.cat_id
      this.paramsForm.attr_id = row.attr_id
      this.paramsForm.attr_name = row.attr_name
      this.paramsForm.attr_sel = this.activeName

      this.isAddDialog = false
      this.paramsDialogVisible = true
    },

    // 删除属性
    deleteParams(row) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const attrVals = []
          row.attr_vals.forEach(item => {
            attrVals.push(item.tag_id)
          })
          const result = await reqDeleteParams(
            row.attr_id,
            this.activeName,
            this.cateId,
            attrVals
          )
          if (result.code === 200) {
            this.$message.success('删除参数成功！')
            // 重新渲染参数表格
            this.tableData = result.data
          } else {
            this.$message.error('删除参数失败！')
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 保存新调整的参数
    saveParams() {
      this.$refs.paramsRef.validate(async valid => {
        if (!valid) return
        let result
        if (this.isAddDialog) {
          // 添加属性
          result = await reqAddParams(this.paramsForm)
        } else {
          // 更新属性
          result = await reqUpdateParams(this.paramsForm)
        }

        if (result.code === 200) {
          this.$message.success(
            `${this.isAddDialog ? '新增' : '修改'}参数成功！`
          )
          // 给每行的input设置单独的值，修复多个input共用一个v-model的值的问题
          result.data.forEach(item => {
            item.tagTnputVisible = false
            item.tagInputValue = ''
          })
          // 重新渲染参数表格
          this.tableData = result.data
        } else {
          this.$message.error(`${this.isAddDialog ? '新增' : '修改'}参数失败！`)
        }

        this.paramsDialogVisible = false
      })
    },

    // 关闭属性对话框
    closeParamsDialog() {
      this.$refs.paramsRef.resetFields()
      this.paramsForm.attr_name = ''
    },

    // 新增tag标签
    showTagInput(row) {
      // 展示输入框
      row.tagTnputVisible = true
      // $nextTick作用：当页面元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // tag标签回车提交或者失去焦点时提交新增标签
    async handleInputConfirm(row) {
      const inputValue = row.tagInputValue.trim()
      if (inputValue) {
        const attrVals = []
        attrVals[0] = inputValue

        const sel = row.attr_sel
        const result = await reqAddTag(row.attr_id, sel, attrVals)

        if (result.code === 200) {
          this.$message.success(
            `${sel === 'many' ? '新增动态参数' : '新增静态属性'}标签成功！`
          )
          // 重新渲染参数表格
          row.attr_vals = result.data.attr_vals
        } else {
          this.$message.error(
            `${sel === 'many' ? '新增动态参数' : '新增静态属性'}标签失败！`
          )
        }
      }

      row.tagTnputVisible = false
      row.tagInputValue = ''
    },

    // 删除标签
    async tagClose(row, i) {
      const attrVals = []
      attrVals[0] = row.attr_vals[i].tag_id
      const result = await reqDeleteTag(row.attr_id, this.activeName, attrVals)
      if (result.code === 200) {
        this.$message.success('删除成功！')
        // 重新渲染参数表格
        row.attr_vals = result.data.attr_vals
      } else {
        this.$message.error('删除失败！')
      }
    }
  }
}
</script>
<style lang='less' scoped>
.el-row {
  margin: 15px 0;
}
.el-cascader {
  width: 100%;
}
.el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
